package com.micro.ai.auth.service.impl;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import com.micro.ai.auth.dto.CaptchaVO;
import com.micro.ai.auth.service.CaptchaService;
import com.micro.ai.auth.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Base64;
import java.util.Properties;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务实现
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Service
public class CaptchaServiceImpl implements CaptchaService {

    @Autowired
    private RedisService redisService;

    @Value("${captcha.expire-time:300}")
    private Integer captchaExpireTime;

    private static final String CAPTCHA_PREFIX = "captcha:";
   // private static final String CAPTCHA_KEY_PREFIX = "captcha:key:";

    /**
     * 创建Kaptcha实例
     */
    private DefaultKaptcha createKaptcha() {
        DefaultKaptcha kaptcha = new DefaultKaptcha();
        Properties properties = new Properties();
        
        // 验证码配置
        properties.setProperty("kaptcha.border", "yes");
        properties.setProperty("kaptcha.border.color", "105,179,90");
        properties.setProperty("kaptcha.textproducer.font.color", "blue");
        properties.setProperty("kaptcha.textproducer.font.size", "30");
        properties.setProperty("kaptcha.textproducer.font.names", "宋体,楷体,微软雅黑");
        properties.setProperty("kaptcha.textproducer.char.length", "4");
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        properties.setProperty("kaptcha.textproducer.char.space", "4");
        properties.setProperty("kaptcha.image.width", "120");
        properties.setProperty("kaptcha.image.height", "40");
        properties.setProperty("kaptcha.noise.color", "white");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.ShadowGimpy");
        
        Config config = new Config(properties);
        kaptcha.setConfig(config);
        
        return kaptcha;
    }

    @Override
    public CaptchaVO generateCaptcha() {
        try {
            // 生成验证码键
            String captchaKey = UUID.randomUUID().toString().replace("-", "");
            
            // 生成验证码文本
            DefaultKaptcha kaptcha = createKaptcha();
            String captchaText = kaptcha.createText();
            
            // 生成验证码图片
            BufferedImage captchaImage = kaptcha.createImage(captchaText);
            
            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(captchaImage, "png", baos);
            byte[] imageBytes = baos.toByteArray();
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            
            // 存储到Redis
            String redisKey = CAPTCHA_PREFIX + captchaKey;
            redisService.set(redisKey, captchaText.toLowerCase(), captchaExpireTime, TimeUnit.SECONDS);
            
            // 构建响应
            CaptchaVO captchaVO = CaptchaVO.builder()
                    .captchaKey(captchaKey)
                    .captchaImage("data:image/png;base64," + base64Image)
                    .expiresIn(captchaExpireTime)
                    .type("image")
                    .build();
            
            log.info("验证码生成成功: key={}, text={}", captchaKey, captchaText);
            return captchaVO;
            
        } catch (Exception e) {
            log.error("验证码生成失败", e);
            throw new RuntimeException("验证码生成失败", e);
        }
    }

    @Override
    public boolean validateCaptcha(String captchaKey, String captchaCode) {
        try {
            if (captchaKey == null || captchaCode == null) {
                return false;
            }
            
            String redisKey = CAPTCHA_PREFIX + captchaKey;
            String storedCode = redisService.get(redisKey, String.class);
            
            if (storedCode == null) {
                log.warn("验证码已过期或不存在: key={}", captchaKey);
                return false;
            }
            
            boolean isValid = storedCode.equals(captchaCode.toLowerCase());
            
            if (isValid) {
                // 验证成功后删除验证码
                deleteCaptcha(captchaKey);
                log.info("验证码验证成功: key={}", captchaKey);
            } else {
                log.warn("验证码验证失败: key={}, input={}, stored={}", captchaKey, captchaCode, storedCode);
            }
            
            return isValid;
            
        } catch (Exception e) {
            log.error("验证码验证失败: key={}, error={}", captchaKey, e.getMessage());
            return false;
        }
    }

    @Override
    public void deleteCaptcha(String captchaKey) {
        try {
            String redisKey = CAPTCHA_PREFIX + captchaKey;
            redisService.delete(redisKey);
            log.debug("验证码已删除: key={}", captchaKey);
        } catch (Exception e) {
            log.error("删除验证码失败: key={}, error={}", captchaKey, e.getMessage());
        }
    }
}
